const router = require('koa-router')();
const Multer = require('@koa/multer');
const fs = require('fs');
const path = require('path');
// @koa/multer 版本太老只能这么引入
const mkdirp = require('mkdirp').mkdirp;

// 前缀
router.prefix('/upload');

// 配置磁盘存储引擎
const storage = Multer.diskStorage({
    // 指定文件保存路径
    destination: (req, file, cb) => {
        let date = new Date();
        let year = date.getFullYear() > 10 ? date.getFullYear() : '0' + date.getFullYear();
        let month = date.getMonth() + 1 > 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1);
        let day = date.getDate() > 10 ? date.getDate() : '0' + date.getDate();
        let dir = "./public/uploads/" + year + '-' + month + '-' + day;

        // 使用 mkdirp 创建目录
        mkdirp(dir, (err) => {
            if (err) {
                return cb(err);
            }
            cb(null, dir);
        });
    },
    // 设置文件名
    filename: (req, file, cb) => {
        cb(null, Date.now() + path.extname(file.originalname));
        // cb(null, '测试文件.jpg');
    }
});

const upload = Multer({ storage });

router.post('/img', upload.single('file'), async ctx => {
    // 获取上传文件的信息
    const file = ctx.request.file;
    let path = ctx.request.file.path
    path = ctx.origin + '' + path.replace('public', '')
    file.url = path
    if (file) {
        console.log('file');
        return ctx.body = {
            code: 200,
            msg: '上传成功',
            data: file
        };
    }
});

module.exports = router;